// pages/Login/LoginIndex.js
var app = getApp();
var requestRoot = app.globalData.hostUrl;
var util = require('../../utils/util.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    iamgeUrl: '',
    formData: {},
    rules: [{
      name: 'username',
      rules: {
        required: true,
        message: '用户名是必填项'
      },
    }, {
      name: 'password',
      rules: {
        required: true,
        message: '密码是必填项'
      },
    }, {
      name: 'code',
      rules: {
        required: true,
        message: '验证码是必填项'
      },
    }]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中',
    })
    var that = this;
    //获取Token
    wx.cloud.init();
    wx.cloud.callFunction({
      name: 'get-csrf-token',
      data: {
        url: requestRoot + '/api/Login/GetToken'
      },
      success: function (res) {
        if (!!res.result) {
          var resobJ=JSON.parse(res.result);
          wx.setStorage({
            key: "csrf-token",
            data: resobJ.csrf_token
          })
          wx.setStorage({
            key: "WEBJSESSIONID",
            data: resobJ.WEBJSESSIONID
          })
        }
      },fail: err => {
        wx.showToast({
          title: '秘钥加载失败',
          icon: 'error',
          duration: 1000
        })
      }
    });
    wx.cloud.callFunction({
      name: 'get-imgcode',
      data: {
        url: requestRoot + '/api/Login/GetImgCode'
      },
      success: function (res) {
        var base64 = 'data:image/jpeg;base64,' +JSON.parse(res.result);
        that.setData({
          iamgeUrl: base64
        });
      },fail: err => {
        wx.hideLoading()
        wx.showToast({
          title: '验证码加载失败',
          icon: 'error',
          duration: 1000
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    wx.hideLoading()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  /**
   * 设置表单数据
   */
  formInputChange: function (e) {
    const { field } = e.currentTarget.dataset
    this.setData({
      [`formData.${field}`]: e.detail.value
    })
  },
  /**
   * 刷新验证码
   */
  changeImage: function () {
    var that = this;
    wx.cloud.callFunction({
      name: 'get-imgcode',
      data: {
        url: requestRoot + '/api/Login/GetImgCode'
      },
      success: function (res) {
        var base64 = 'data:image/jpeg;base64,' +JSON.parse(res.result);
        that.setData({
          iamgeUrl: base64
        });
      }
    })
  },
  /**
   * 登录
   */
  submitForm: function (e) {
    this.selectComponent('#form').validate((valid, errors) => {
      if (!valid) {
        const firstError = Object.keys(errors)
        if (firstError.length) {
          this.setData({
            error: errors[firstError[0]].message
          })

        }
      } else {
        this.GetLogin(this.data.formData);
      }
    })
  },
  GetLogin: function (formdata) {
    wx.showLoading({
      title: '登录中'
    })
    formdata._csrf = wx.getStorageSync('csrf-token');
    formdata.WEBJSESSIONID = wx.getStorageSync('WEBJSESSIONID');
    formdata.url = requestRoot + '/api/Login/LoginPMS';
    wx.cloud.callFunction({
      name: 'LoginPMS',
      data: formdata,
      success: function (res) {
        let resInfo = res.result;
        if (resInfo.code == 200) {
          let info = resInfo.info;
          var cookieData = resInfo.data;
          var sessionObj = cookieData.cookieList.find(function (ele) {
            return ele.m_name == "WEBJSESSIONID"
          });
          //WEBJSESSIONID
          wx.setStorage({
            data: sessionObj.m_value,
            key: sessionObj.m_name,
          }),
            //token值
            wx.setStorage({
              data: cookieData.token,
              key: 'csrf-token',
            }),
            //姓名
            wx.setStorage({
              data: cookieData.userName,
              key: 'userName',
            }),
            //用户Id
            wx.setStorage({
              data: cookieData.userId,
              key: 'userId',
            })
          wx.hideLoading()
          wx.showToast({
            title: '登录成功',
            icon: 'success',
            duration: 1000
          })
          wx.switchTab({
            url: '/pages/CNKIProject/ProjectMenu',
          })
        }else
        {
          wx.hideLoading();
          wx.showToast({
            title: resInfo.info,
            icon: 'error',
            duration: 1000
          })
        }

      },
      fail: err => {
        wx.hideLoading()
        wx.showToast({
          title: '登陆失败',
          icon: 'error',
          duration: 1000
        })
      },
    })
  }
})